<script lang="ts" setup>
import { ref, watch, reactive } from "vue"
import { usePagination } from "@/hooks/usePagination"
import { type IGetOrderData } from "@/api/order/types/order"
import { formatDateTime } from "@/utils"
import { Search, Refresh } from "@element-plus/icons-vue"
import { ElTable, type FormInstance } from "element-plus"
import { useComboStore } from "@/store/modules/combo"
import { getOrderDataApi, getOrdeCode } from "@/api/order"
import { shortcuts } from "@/utils/dateSet"

defineOptions({
  name: "DistributionOrder"
})
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const tableData = ref<IGetOrderData[]>([])
const comboStore = useComboStore()
const comboList = ref<any>([])
const loading = ref<boolean>(false)
// #region 搜索
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const searchData = reactive({
  id: "", // id
  source: "API", // 订单来源
  sku: "", //  套餐
  superName: "", //  上级名
  cardName: "", //  身份证姓名
  orderOutId: "", // 外部id
  handleMobile: "", // 入网号
  cardId: "", // 身份证号
  takeMobile: "", // 收货电话
  time: "", // 创建时间
  update: "", // 更新时间
  state: "", // 订单状态
  re_id: "" // 推荐人
})
const searchFormRef = ref<FormInstance | null>(null)
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion

const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.sku) {
      celValue = item.name
    }
  })
  return celValue
}

const getTableData = () => {
  loading.value = true
  getOrderDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    id: searchData.id,
    orderOutId: searchData.orderOutId,
    start: new Date(searchData.time[0]).getTime() || "",
    end: new Date(searchData.time[1]).getTime() || "",
    updateStart: new Date(searchData.update[0]).getTime() || "",
    updateEnd: new Date(searchData.update[1]).getTime() || "",
    source: searchData.source,
    sku: searchData.sku,
    handleMobile: searchData.handleMobile,
    superName: searchData.superName,
    cardName: searchData.cardName,
    cardId: searchData.cardId,
    takeMobile: searchData.takeMobile,
    re_id: searchData.re_id,
    state: searchData.state || 0
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.orderList
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听套餐缓存(pinia) */
comboStore.getComoboFn()
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**E N D */

/**监听代理账号缓存(pinia) */
import { useReStore } from "@/store/modules/reId"
const reStore = useReStore()
reStore.getReFn()
const reList = ref<any>([])
watch(
  [() => reStore.reListStore],
  (newValue) => {
    reList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**E N D */

const codeList = ref<any>([])
/**-------- */
const getCodeList = () => {
  getOrdeCode().then((res: any) => {
    // console.log(res)
    codeList.value = res.data
  })
}
getCodeList()
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="订单ID">
          <el-input v-model.trim="searchData.id" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="orderOutId" label="外部ID">
          <el-input v-model.trim="searchData.orderOutId" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="time" label="创建时间">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <!-- <el-form-item prop="update" label="反馈时间">
          <el-date-picker
            v-model="searchData.update"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime1"
          />
        </el-form-item> -->
        <el-form-item prop="source" label="订单来源">
          <el-input v-model.trim="searchData.source" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="sku" label="套餐">
          <el-select v-model="searchData.sku" clearable filterable placeholder="请选套餐">
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <el-form-item prop="handleMobile" label="入网号">
          <el-input v-model.trim="searchData.handleMobile" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="superName" label="上级名">
          <el-input v-model.trim="searchData.superName" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardName" label="身份证姓名">
          <el-input v-model.trim="searchData.cardName" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardId" label="身份证号">
          <el-input v-model.trim="searchData.cardId" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="takeMobile" label="收货电话">
          <el-input v-model.trim="searchData.takeMobile" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="re_id" label="推荐人">
          <el-select v-model="searchData.re_id" clearable filterable placeholder="请选推荐人" style="width: 240px">
            <el-option v-for="item in reList" :key="item.user_id" :label="item.user_name" :value="item.user_id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-select v-model="searchData.state" clearable placeholder="请选择">
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="orderId" label="外部ID" align="center" />
          <el-table-column prop="create" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.create) }}
            </template>
          </el-table-column>
          <el-table-column prop="update" label="反馈时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.update) }}
            </template>
          </el-table-column>
          <el-table-column prop="source" label="订单来源" align="center" />
          <el-table-column prop="reName" label="推荐人" align="center" />
          <el-table-column prop="sku" label="套餐" align="center" :formatter="formatterCombo" show-overflow-tooltip />
          <el-table-column prop="handleMobile" label="入网号" align="center" />
          <el-table-column prop="superiorName" label="上级名" align="center" />
          <!-- <el-table-column prop="iccid" label="ICCID" align="center" /> -->
          <el-table-column prop="cardName" label="身份证姓名" align="center" />
          <el-table-column prop="cardId" label="身份证号" align="center" />
          <el-table-column prop="consignee" label="收货人" align="center" />
          <el-table-column prop="takeMobile" label="收货电话" align="center" />
          <el-table-column prop="takeAddress" label="收货地址" align="center" show-overflow-tooltip />
          <el-table-column label="订单状态" align="center">
            <template #default="scope">
              <div
                :class="{
                  doing: scope.row.state.code <= 200 && scope.row.state.code > 199,
                  success: scope.row.state.code >= 100 && scope.row.state.code < 200,
                  error: scope.row.state.code >= 400,
                  again: scope.row.state.code < 0
                }"
              >
                {{ scope.row.state.state }}
                <div class="text-ellipsis" v-if="scope.row.result" style="font-size: 12px">
                  <el-tooltip placement="top">
                    <template #content> {{ scope.row.result }} </template>
                    <span style="cursor: pointer">({{ scope.row.result }})</span>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="物流状态" align="center" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.logisticsState.str }}
            </template>
          </el-table-column>
          <el-table-column prop="chargingState" label="充值情况" align="center" show-overflow-tooltip />
          <!-- <el-table-column fixed="right" label="操作" width="140" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                :disabled="scope.row.state.code < 400"
                >重新提交</el-button
              ><br /><br />
              <el-button type="primary" text bg size="small" @click="handleSeeMore(scope.row)"> 查看详情</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
